import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import { parseArgs } from "node:util";
import esbuild from "esbuild";
import { createRequire } from "node:module";

const {
  values: { format },
  positionals,
} = parseArgs({
  allowPositionals: true, // 允许位置参数
  options: {
    format: {
      type: "string",
      short: "f",
      default: "esm",
    },
  },
});

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);

const target = positionals.length ? positionals[0] : "vue"; // 模块名称
const entry = resolve(__dirname, `../packages/${target}/src/index.ts`); // 打包入口地址

const outfile = resolve(
  __dirname,
  `../packages/${target}/dist/${target}.${format}.js`
); // 打包输出地址

const pkg = require(`../packages/${target}/package.json`);

esbuild
  .context({
    entryPoints: [entry],
    bundle: true,
    platform: format === "cjs" ? "node" : "browser",
    sourcemap: true,
    outfile,
    format,
    globalName: pkg.buildOptions.name,
  })
  .then((ctx) => {
    ctx.watch();
  })
  .catch((err) => {});
